﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;

using FingerPrint.WebUI.ViewModels;
using FingerPrint.WebUI.DAL;
using FingerPrint.WebUI.Models;

using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;

namespace FingerPrint.WebUI.Controllers
{
    public class TestController : Controller
    {
        private FingerPrintContext db = new FingerPrintContext();

        private UnitOfWork unitOfWork = new UnitOfWork();

        public ViewResult Index()
        {
            PopulateEmployees();                            // Populate a list of employees to be used in Filter
            return View(GetAllSalesOrders().ToList());
        }

        private void PopulateSelectedProductData(SalesOrder salesOrder)
        {
            var allProducts = db.Products;
            var salesOrderProducts = new HashSet<int>(salesOrder.Products.Select(p => p.ProductID));

            var viewModel = new List<SelectedSalesOrderProducts>();
            foreach (var product in allProducts)
            {
                viewModel.Add(new SelectedSalesOrderProducts
                {
                    ProductID = product.ProductID,
                    Description = product.Description,
                    ProductCategoryID = product.ProductCategoryID,
                    ProductGroupID = product.ProductGroupID,
                    GroupNumber = product.ProductGroup.GroupNumber,

                    Selected = salesOrderProducts.Contains(product.ProductID)
                });
            }
            ViewBag.Products = viewModel;
        }

        //
        // GET: /Product/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Product/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Product/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: /SalesOrder/Edit/5
        public ActionResult Edit(int id)
        {
            SalesOrder salesOrder = unitOfWork.SalesOrderRepository.GetByID(id);

            PopulateSelectedProductData(salesOrder);
            PopulateEmployeesDropDownList(salesOrder.EmployeeID);
            PopulateCustomersDropDownList(salesOrder.CustomerID);

            return View(salesOrder);
        }


        //public ActionResult Edit(int id)
        //{
        //    SalesOrder salesorder = unitOfWork.SalesOrderRepository.GetByID(id);
        //    PopulateEmployeesDropDownList(salesorder.EmployeeID);
        //    PopulateCustomersDropDownList(salesorder.CustomerID);
        //    return View(salesorder);
        //}

        //
        // POST: /SalesOrder/Edit/5
        [HttpPost]
        public ActionResult Edit(SalesOrder salesOrder)
        {
            try
            {

                if (ModelState.IsValid)
                {
                    unitOfWork.SalesOrderRepository.Update(salesOrder);
                    unitOfWork.Save();
                    //db.Entry(salesorder).State = EntityState.Modified;
                    //db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (DataException)
            {
                //Log the error (add a variable name after DataException)
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
            }
            PopulateEmployeesDropDownList(salesOrder.EmployeeID);
            PopulateCustomersDropDownList(salesOrder.CustomerID);
            return View(salesOrder);

        }


        //
        // GET: /Product/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Product/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }


        // -----------------------------
        // --- Functions and Methods ---
        // -----------------------------

        // Populate the list of Employees
        private void PopulateEmployeesDropDownList(object selectedEmployee = null)
        {
            var employeesQuery = unitOfWork.EmployeeRepository.Get(
                orderBy: q => q.OrderBy(d => d.EngName));
            ViewBag.EmployeeID = new SelectList(employeesQuery, "EmployeeID", "EngName", selectedEmployee);
        }


        // Populate the list of Customers
        private void PopulateCustomersDropDownList(object selectedCustomer = null)
        {
            var customersQuery = unitOfWork.CustomerRepository.Get(
                orderBy: q => q.OrderBy(d => d.CompanyCode));
            ViewBag.CustomerID = new SelectList(customersQuery, "CustomerID", "CompanyCode", selectedCustomer);
        }


        private IEnumerable<SalesOrderModel> GetAllSalesOrders()
        {
            var allSalesOrders = unitOfWork.SalesOrderRepository
                    .Get(includeProperties: "Employee, Customer")
                    .Select(so => new SalesOrderModel
                    {
                        SalesOrderID = so.SalesOrderID,
                        SalesOrderNumber = so.SalesOrderNumber,
                        ReceivedDate = so.ReceivedDate,

                        //EmployeeID = so.EmployeeID, //so.EmployeeID ?? 0,
                        Employee = so.Employee,
                        Customer = so.Customer,

                        //CustomerID = so.CustomerID,
                        Deadline = so.Deadline,
                        InvoiceNumber = so.InvoiceNumber,
                        Remark = so.Remark,
                        Status = so.Status,
                        ModifiedDate = so.ModifiedDate
                    })
                    .OrderByDescending(so => so.SalesOrderID);
            return (allSalesOrders);
        }


        
        // Function to populate a list of Employees
        private void PopulateEmployees()
        {
            var employees = unitOfWork.EmployeeRepository
                .Get()
                .Select(e => new EmployeeViewModel
                {
                    EmployeeID = e.EmployeeID,
                    EmployeeName = e.EngName
                })
                .OrderBy(e => e.EmployeeName);

            ViewData["employees"] = employees;
            ViewData["defaultEmployees"] = employees.First();
        }


        // populate the filtered list of Employee
        public ActionResult FilterMenu_Employee()
        {
            return Json(db.SalesOrders.Select(so => so.Employee.EngName).Distinct(), JsonRequestBehavior.AllowGet);
        } 

    }
}
